package com.ihr360.cnb.module.payroll.job;

import com.google.common.collect.Lists;
import com.ihr360.cnb.module.payroll.service.IrenshiAttendanceDubboProviderService;
import com.ihr360.cnb.module.payroll.service.PayrollService;
import com.ihr360.commons.entity.AuthUserInfo;
import com.ihr360.commons.exception.Ihr360Exception;
import com.ihr360.commons.lang.CollectionUtils;
import com.ihr360.commons.lang.DateUtils;
import com.ihr360.commons.model.type.ProgressType;
import com.ihr360.payroll.request.attendance.AttendanceSyncRequest;
import com.ihr360.payroll.request.attendance.AttendanceTakeNumberRequest;
import com.ihr360.payroll.response.attendance.AttendanceBillSyncResponse;
import com.ihr360.payroll.response.attendance.AttendanceSyncResponse;
import com.ihr360.sharedservice.api.DataCacheService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;

/**
 * Created by Eric on 2018/4/10/010.
 */
@Component
public class AttendanceSyncJob {

    private final Logger logger = LoggerFactory.getLogger(AttendanceSyncJob.class);

    private static final int SYNC_LIST_SIZE = 10;

    @Autowired
    private PayrollService payrollService;

    @Autowired
    private IrenshiAttendanceDubboProviderService irenshiAttendanceDubboProviderService;

    @Autowired
    private DataCacheService dataCacheService;

    private List<List<String>> splitStaffList(List<String> staffIdList) {
        if (CollectionUtils.isEmpty(staffIdList)) {
            throw new Ihr360Exception(null, "考勤汇总员工列表为空！");
        }
        List<List<String>> result = Lists.newArrayList();
        int size = staffIdList.size();
        int count = (size + SYNC_LIST_SIZE - 1) / SYNC_LIST_SIZE;
        for (int i = 0; i < count; i++) {
            int limit = (i + 1) * SYNC_LIST_SIZE > size ? size : SYNC_LIST_SIZE * (i + 1);
            List<String> subList = staffIdList.subList(i * SYNC_LIST_SIZE, limit);
            result.add(subList);
        }
        return result;
    }

    @Async
    public void takeNumberMonthlyReport(AttendanceTakeNumberRequest request) {
        Long summaryId = request.getSummaryId();
        List<String> staffIds = request.getStaffIds();
        //根据员工列表分批次查询考勤数据
        try {
            List<List<String>> lists = splitStaffList(staffIds);
            AttendanceSyncResponse monthResponse = new AttendanceSyncResponse();
            int size = lists.size();
            for (int i = 0; i < size; i++) {
                //进度
                AttendanceTakeNumberRequest limitRequest = new AttendanceTakeNumberRequest();
                BeanUtils.copyProperties(request, limitRequest);
                limitRequest.setStaffIds(lists.get(i));
                AttendanceSyncRequest limitSyncRequest = this.getSyncRequest(limitRequest.getUserInfo(), limitRequest);
                List<AttendanceBillSyncResponse> limitBillList = Lists.newArrayList();
                //获取月报
                monthResponse = irenshiAttendanceDubboProviderService.getSignMonthlyReportInfoData(limitSyncRequest);
                //获取日报数据
                limitBillList = irenshiAttendanceDubboProviderService.getSignRecordInfoData(limitSyncRequest);
                //合计数据
                limitRequest.setBillList(limitBillList);
                limitRequest.setMonthResponse(monthResponse);
                payrollService.takeNumberMonthlyReport(limitRequest);
                BigDecimal currentSize = new BigDecimal(i + 1);
                BigDecimal currentProgress = currentSize.divide(new BigDecimal(size),2).multiply(new BigDecimal(100));
                String progress = String.valueOf(currentProgress.intValue());
                dataCacheService.put(ProgressType.ATTENDANCE_SUMMARY.name() + summaryId, progress);
            }
            //完成同步
            dataCacheService.remove(ProgressType.ATTENDANCE_SUMMARY.name() + request.getSummaryId());
        } catch (Exception e) {
            logger.error("考勤同步接口异常");
            logger.error(e.getMessage(), e);
            //回滚汇总数据
            payrollService.rollBackAttendanceSummaryData(summaryId);
        }
    }

    private AttendanceSyncRequest getSyncRequest(AuthUserInfo userInfo, AttendanceTakeNumberRequest takeNumberRequest) {
        //获取月报数据
        AttendanceSyncRequest syncRequest = new AttendanceSyncRequest();
        syncRequest.setCompanyId(userInfo.getCompanyId());
        syncRequest.setStartDate(DateUtils.getMinDateInDay(takeNumberRequest.getSummaryStartDate()));
        syncRequest.setEndDate(DateUtils.getMaxDateInDay(takeNumberRequest.getSummaryEndDate()));
        syncRequest.setOverTimeStartDate(DateUtils.getMinDateInDay(takeNumberRequest.getOverTimeStartDate()));
        syncRequest.setOverTimeEndDate(DateUtils.getMaxDateInDay(takeNumberRequest.getOverTimeEndDate()));
        syncRequest.setStaffIdList(takeNumberRequest.getStaffIds());
        return syncRequest;
    }


}
